package org.hs.phd.common.geometry;

import java.awt.Polygon;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LinearRing;

public final class PolygonUtils {

	private static GeometryFactory factory;
	
	static{
		factory = new GeometryFactory();
	}

	private PolygonUtils(){
	}

	public static double getPolygonalIntersectionArea(Polygon p1, Polygon p2) {
		
		
		com.vividsolutions.jts.geom.Polygon jtsP1 = convertToJTSPolygon(p1);		
		com.vividsolutions.jts.geom.Polygon jtsP2 = convertToJTSPolygon(p2);
		
		return jtsP1.intersection(jtsP2).getArea();
		
	}

	private static com.vividsolutions.jts.geom.Polygon convertToJTSPolygon(Polygon polygon) {
		
		Coordinate[] coords = new Coordinate[polygon.npoints + 1];
		
		for (int i = 0; i < polygon.npoints; i++) {
			coords[i] = new Coordinate(polygon.xpoints[i], polygon.ypoints[i]);
		}
		coords[polygon.npoints] = new Coordinate(polygon.xpoints[0], polygon.ypoints[0]);
		
		LinearRing ring = factory.createLinearRing(coords);
		
		com.vividsolutions.jts.geom.Polygon jtsPolygon = factory.createPolygon(ring, null);
		
		return jtsPolygon;
	}

	public static double getPolygonalArea(Polygon polygon) {
		return convertToJTSPolygon(polygon).getArea();
	}
	
	
	
}
